package org.evil.deus.rss.widget;

import org.evil.deus.rss.CursorUtils;
import org.evil.deus.rss.R;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;

public class RSSWidget extends AppWidgetProvider {
	
	public interface Widget extends BaseColumns {
		public static final String TABLE = "widgets";
		public static final Uri CONTENT_URI = new Uri.Builder()
											  .authority(RSSWidgetProvider.AUTHORITY)
											  .scheme(ContentResolver.SCHEME_CONTENT)
											  .appendPath(TABLE)
											  .build();
		
		public static final String ID = "app_widget_id";
		public static final String URL = "url";
	}
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		Intent intent = new Intent(context.getString(R.string.action_update_widget));
		intent.putExtra(RSSWidgetUpdateService.EXTRA_APPWIDGETID, appWidgetIds);
		context.startService(intent);
	}
	
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		Intent intent = new Intent(context.getString(R.string.action_sync));
        context.startService(intent);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent != null && intent.getAction().equals(context.getString(R.string.action_sync_end))) {
			onUpdate(context, AppWidgetManager.getInstance(context), getAppWidgetIds(context));
		} else {
			super.onReceive(context, intent);
		}
	}
	
	private int [] getAppWidgetIds(Context context) {
		Cursor cursor = context.getContentResolver().query(RSSWidget.Widget.CONTENT_URI, 
														   new String [] {RSSWidget.Widget.ID}, 
														   null, 
														   null, 
														   null);
		int [] result = new int [0];
		int count = cursor.getCount();
		if (count > 0 && cursor.moveToFirst()) {
			result = new int[count];
			for (int i = 0; cursor.moveToNext(); i++) {
				result[i] = CursorUtils.getInt(cursor, RSSWidget.Widget.ID);
			}
		}
		return result;
	}
}
